$import( "SmitearWebGL.Objects.Parser.Collada.DaeEntity" );
$import( "SmitearWebGL.Objects.Parser.Collada.DaeVertices" );
$import( "SmitearWebGL.Objects.Parser.Collada.DaeInput" );
$import( "SmitearWebGL.Objects.Parser.Collada.DaePrimitive" );

SmitearWebGL.Objects.Parser.Collada.DaeMesh = SmitearWebGL.Objects.Parser.Collada.DaeEntity.extend(
{
	/******** constructor ********/

	init : function( document, geometry, node )
	{
		this.geometry = geometry;
		this.vertices = null;
		this.primitives = null;

		this._super( document, node );
		this._registClass( "SmitearWebGL.Objects.Parser.Collada.DaeMesh" );
	}
	,
	destroy : function()
	{
		this._super();

		if ( this.vertices )
		{
			this.vertices.destroy();
			this.vertices = null;
		}

		if ( this.primitives )
		{
			for ( var primitive in this.primitives )
			{
				this.primitives[primitive].destroy();
			}
			this.primitives = null;
		}

		this.geometry = null;
	}
	,
	read : function( node )
	{
		if ( node.localName != SmitearWebGL.Objects.Parser.Collada.Const.DAE_MESH_ELEMENT && node.localName != SmitearWebGL.Objects.Parser.Collada.Const.DAE_CONVEX_MESH_ELEMENT )
		$THROW( false, "expected a '" + SmitearWebGL.Objects.Parser.Collada.Const.DAE_MESH_ELEMENT + " or a '" + SmitearWebGL.Objects.Parser.Collada.Const.DAE_CONVEX_MESH_ELEMENT + "' element" );

		this._super( node );

		this.primitives = [];

		// fetch <vertices> element
		var verticesNode = this.getNode( node, SmitearWebGL.Objects.Parser.Collada.Const.DAE_VERTICES_ELEMENT );

		this.vertices = new SmitearWebGL.Objects.Parser.Collada.DaeVertices( this.document, verticesNode );

		var inputList = this.getNodeList(verticesNode, SmitearWebGL.Objects.Parser.Collada.Const.DAE_INPUT_ELEMENT);

		for( var i = 0; i < inputList.length; i++ )
		{
			var input = new SmitearWebGL.Objects.Parser.Collada.DaeInput( this.document, inputList[i] );
			if( input.semantic == "POSITION" )
			{
				this.vertices.source = this.document.sources[ input.source ];
			}
		}

		var children = node.childNodes;
		
		for( var i = 0; i < children.length; i++ )
		{
			var child = children[i];

			switch( child.localName )
			{
				case SmitearWebGL.Objects.Parser.Collada.Const.DAE_TRIANGLES_ELEMENT:
				case SmitearWebGL.Objects.Parser.Collada.Const.DAE_TRIFANS_ELEMENT:
				case SmitearWebGL.Objects.Parser.Collada.Const.DAE_TRISTRIPS_ELEMENT:
				case SmitearWebGL.Objects.Parser.Collada.Const.DAE_LINESTRIPS_ELEMENT:
				case SmitearWebGL.Objects.Parser.Collada.Const.DAE_LINES_ELEMENT:
				case SmitearWebGL.Objects.Parser.Collada.Const.DAE_POLYGONS_ELEMENT:
				case SmitearWebGL.Objects.Parser.Collada.Const.DAE_POLYLIST_ELEMENT:
					var primitive = new SmitearWebGL.Objects.Parser.Collada.DaePrimitive( this.document, this, child );
					if( primitive.count > 0 )
					{
						this.primitives.push( primitive );
					}
					break;
				default:
					break;
			}
		}
	}
}
);